<html lang="zh">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
        <meta name="description" content="孤独症行为量表(ABC)家长自助评定工具，帮助家长初步了解孩子的发展情况，通过评估儿童在感觉、交往、身体和目标物的使用、语言以及自理能力和社会适应等方面的表现，及早发现潜在问题。">
        <meta name="keywords" content="孤独症行为量表, ABC量表, 孤独症筛查, 儿童发展评估, 自闭症评估, 家长自助评定, 孤独症早期干预">
        <meta name="custom-image" content="https://totemlife.cn/apps/public/abc-scale-cover.jpg">
        <title>孤独症行为量表评定(ABC)</title>
        <script src="/apps/js/baidu-tongji-mtx.js"></script>
        <link href="/apps/css/bootstrap.min.css" rel="stylesheet">
        <link href="/apps/css/fontawesome-free-6.4.0-web/css/all.css" rel="stylesheet">
        <style>
            /* 自定义橙色背景类 */
            .bg-orange {
                background-color: #fd7e14;
            }

            /* 移动端优化 */
            @media (max-width: 576px) {
                .btn-group {
                    flex-wrap: wrap;
                }

                .btn-group .btn {
                    flex: 1 0 18%;
                    margin: 2px;
                }

                /* 表格响应式优化 */
                .table-responsive {
                    font-size: 0.875rem;
                }

                /* 历史记录表格优化 */
                .history-table th:nth-child(3),
                .history-table td:nth-child(3) {
                    display: none;
                }

                /* 操作按钮优化 */
                .action-btns .btn {
                    padding: 0.25rem 0.5rem;
                    font-size: 0.75rem;
                }

                /* 标题优化 */
                h1 {
                    font-size: 1.75rem;
                }

                h5 {
                    font-size: 1.1rem;
                }

                /* 表单元素优化 */
                .form-control, .form-select {
                    font-size: 1rem;
                    height: 45px; /* 增大触摸区域 */
                }

                /* 提交按钮优化 */
                .submit-btn {
                    height: 50px;
                    font-size: 1.1rem;
                }
            }

            /* 页面样式 */
            body {
                background-color: #f8f9fa;
                padding-bottom: 60px;
            }

            footer {
                position: fixed;
                bottom: 0;
                width: 100%;
                background-color: rgba(15, 76, 129, 0.8);
                color: white;
                padding: 10px 15px;
                display: flex;
                justify-content: center;
                align-items: center;
                z-index: 1000;
            }
        </style>
    </head>
    <body>
{{!-- ABC孤独症行为量表评定页面 --}}
<div class="container mt-4 mb-5">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h1>孤独症行为量表(ABC)</h1>
                <a href="/apps/scales/scales-dashboard" class="btn btn-outline-secondary">
                    <i class="fas fa-th-large"></i> 量表工具
                </a>
            </div>
            <div class="card shadow-sm mb-4">
                <div class="card-body">
                    <h5 class="card-title">关于ABC量表</h5>
                    <p class="card-text">
                        孤独症行为量表(Autism Behavior Checklist, ABC)是一种用于筛查孤独症的工具，通过评估儿童在感觉、交往、身体和目标物的使用、语言以及自理能力和社会适应等方面的表现，帮助家长初步了解孩子的发展情况。
                    </p>
                    <p class="card-text">
                        <strong>注意：</strong>本评估仅供参考，不能替代专业医疗机构的诊断。如有疑虑，请及时咨询专业医师。
                    </p>
                </div>
            </div>

            {{#if assessmentHistory.length}}
            <div class="card shadow-sm mb-4">
                <div class="card-header bg-light">
                    <h5 class="mb-0">历史评估记录</h5>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover mb-0 history-table">
                            <thead>
                                <tr>
                                    <th>日期</th>
                                    <th>姓名</th>
                                    <th>年龄</th>
                                    <th>总分</th>
                                    <th>结果</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                {{#each assessmentHistory}}
                                <tr>
                                    <td>{{formatDate assessment_date "YYYY-MM-DD HH:mm:ss"}}</td>
                                    <td>{{child_name}}</td>
                                    <td>{{child_age}}岁</td>
                                    <td>{{total_score}}</td>
                                    <td>
                                        <span class="badge {{#if (eq result_level '正常')}}bg-success{{else if (eq result_level '轻度')}}bg-warning{{else if (eq result_level '中度')}}bg-orange{{else}}bg-danger{{/if}}">
                                            {{result_level}}
                                        </span>
                                    </td>
                                    <td class="action-btns">
                                        <a href="/apps/scales/abc-scale/result/{{id}}" class="btn btn-sm btn-outline-primary">查看</a>
                                        <a href="/apps/scales/abc-scale/report/{{id}}" class="btn btn-sm btn-outline-secondary">报告</a>
                                    </td>
                                </tr>
                                {{/each}}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            {{/if}}

            <div class="card shadow-sm">
                <div class="card-body">
                    <h5 class="card-title">开始新评估</h5>
                    <p class="card-text">请填写基本信息，然后开始评估。</p>

                    <form id="childInfoForm" class="mb-3">
                        <div class="row g-3">
                            <div class="col-md-4">
                                <label for="childName" class="form-label">姓名</label>
                                <input type="text" class="form-control" id="childName" required>
                            </div>
                            <div class="col-md-4">
                                <label for="childAge" class="form-label">年龄</label>
                                <input type="number" class="form-control" id="childAge" min="1" max="18" required>
                            </div>
                            <div class="col-md-4">
                                <label for="childGender" class="form-label">性别</label>
                                <select class="form-select" id="childGender" required>
                                    <option value="">请选择</option>
                                    <option value="男">男</option>
                                    <option value="女">女</option>
                                </select>
                            </div>
                        </div>
                        <div class="mt-3">
                            <button type="submit" class="btn btn-primary w-100 submit-btn">开始评估</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

{{!-- 评估问卷模态框 --}}
<div class="modal fade" id="assessmentModal" tabindex="-1" aria-labelledby="assessmentModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-scrollable modal-fullscreen-sm-down">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="assessmentModalLabel">ABC孤独症行为量表评估</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div id="assessmentProgress" class="progress mb-3" style="height: 10px;">
                    <div class="progress-bar" role="progressbar" style="width: 0%;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
                </div>

                <form id="assessmentForm">
                    <div id="questionsContainer">
                        {{!-- 问题将通过JavaScript动态加载 --}}
                        <div class="text-center py-5">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">加载中...</span>
                            </div>
                            <p class="mt-2">正在加载问题...</p>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="prevCategoryBtn" style="display: none;">上一类</button>
                <button type="button" class="btn btn-primary" id="nextCategoryBtn">下一类</button>
                <button type="button" class="btn btn-success" id="submitAssessmentBtn" style="display: none;">提交评估</button>
            </div>
        </div>
    </div>
</div>

{{!-- 结果模态框 --}}
<div class="modal fade" id="resultModal" tabindex="-1" aria-labelledby="resultModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-fullscreen-sm-down">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="resultModalLabel">评估结果</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="text-center mb-3">
                    <div id="resultIcon" class="mb-3">
                        <i class="fas fa-check-circle text-success fa-4x"></i>
                    </div>
                    <h4 id="resultTitle">评估完成</h4>
                    <p id="resultScore" class="fs-5">总分: <span>0</span></p>
                    <p id="resultLevel" class="fs-5">结果: <span>正常</span></p>
                    <p id="resultDescription" class="mt-3">您的孩子目前表现为正常范围，无需特别关注。</p>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <a href="#" id="viewResultBtn" class="btn btn-primary">查看详细结果</a>
            </div>
        </div>
    </div>
</div>

{{!-- 自定义确认框 --}}
<div class="modal fade" id="customConfirmModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">提示</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p id="customConfirmMessage"></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="customConfirmYesBtn">确定</button>
            </div>
        </div>
    </div>
</div>

{{!-- 警告模态框 --}}
<div class="modal fade" id="warningModal" tabindex="-1" aria-labelledby="warningModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="warningModalLabel">提示</h5>
            </div>
            <div class="modal-body">
                <p id="warningMessage"></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" data-bs-dismiss="modal">继续作答</button>
            </div>
        </div>
    </div>
</div>

<!-- Footer -->
<footer>
    <div class="text-center">
        <a id="tmall-app-home-link" href="weixin://dl/business/?appid=wx1b441d1a37b278e1&path=pages/index/index&env_version=release" class="text-decoration-none">
            <span id="tmall-app-home-title" style="color: white; font-size: 16px; margin-left: 5px;">
                <i class="fa fa-house"></i> 广州图腾生命医学研究有限公司
            <span>
        </a>
        &copy; {{currentYear}}
    </div>
</footer>

        <!-- 将所有JS文件移到这里，并添加defer属性 -->
        <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js" defer></script>
        <script src="/apps/js/bootstrap.bundle.min.js" defer></script>
        <script src="/apps/js/wx-client-dom.js" defer></script>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 全局变量
        let categories = [];
        let questions = {};
        let currentCategory = 0;
        let answers = {};
        let childInfo = {};

        // 获取DOM元素
        const childInfoForm = document.getElementById('childInfoForm');
        const assessmentModal = new bootstrap.Modal(document.getElementById('assessmentModal'));
        const resultModal = new bootstrap.Modal(document.getElementById('resultModal'));
        const warningModal = new bootstrap.Modal(document.getElementById('warningModal'));
        const warningMessage = document.getElementById('warningMessage');
        const questionsContainer = document.getElementById('questionsContainer');
        const prevCategoryBtn = document.getElementById('prevCategoryBtn');
        const nextCategoryBtn = document.getElementById('nextCategoryBtn');
        const submitAssessmentBtn = document.getElementById('submitAssessmentBtn');
        const progressBar = document.querySelector('#assessmentProgress .progress-bar');

        // 自定义确认框
        const customConfirmModal = new bootstrap.Modal(document.getElementById('customConfirmModal'));
        const customConfirmMessage = document.getElementById('customConfirmMessage');
        const customConfirmYesBtn = document.getElementById('customConfirmYesBtn');

        // 自定义确认框函数
        function showCustomConfirm(message, callback) {
            customConfirmMessage.textContent = message;
            customConfirmYesBtn.onclick = function() {
                customConfirmModal.hide();
                callback(true);
            };
            customConfirmModal.show();

            // 当模态框隐藏时，如果是通过关闭按钮或取消按钮，则返回 false
            const modalElement = document.getElementById('customConfirmModal');
            const onHidden = function() {
                if (customConfirmYesBtn.onclick) {
                    callback(false);
                    customConfirmYesBtn.onclick = null;
                }
                modalElement.removeEventListener('hidden.bs.modal', onHidden);
            };
            modalElement.addEventListener('hidden.bs.modal', onHidden);
        }

        // 显示警告信息的函数
        function showWarning(message) {
            warningMessage.textContent = message;
            warningModal.show();
        }

        // 提交儿童信息表单
        childInfoForm.addEventListener('submit', function(e) {
            e.preventDefault();

            // 获取儿童信息
            childInfo = {
                childName: document.getElementById('childName').value,
                childAge: document.getElementById('childAge').value,
                childGender: document.getElementById('childGender').value
            };

            // 加载问题并显示评估模态框
            loadQuestions();
            assessmentModal.show();
        });

        // 加载问题
        async function loadQuestions() {
            try {
                const response = await fetch('/apps/scales/abc-scale/questions');
                const data = await response.json();

                if (data.success) {
                    categories = data.categories;
                    questions = data.questions;

                    // 显示第一类问题
                    showCategory(1);
                } else {
                    alert('加载问题失败: ' + data.message);
                }
            } catch (error) {
                console.error('加载问题错误:', error);
                alert('加载问题失败，请稍后重试');
            }
        }

        // 显示指定类别的问题
        function showCategory(categoryId) {
            currentCategory = categoryId;

            // 更新进度条
            const progress = (categoryId - 1) / categories.length * 100;
            progressBar.style.width = progress + '%';
            progressBar.setAttribute('aria-valuenow', progress);

            // 获取当前类别的问题
            const categoryQuestions = questions[categoryId] || [];
            const category = categories.find(c => c.id === categoryId) || { name: '未知类别' };

            // 构建问题HTML
            let html = `
                <div class="mb-4">
                    <h4 class="mb-3">第${categoryId}部分: ${category.name}</h4>
                    <p class="text-muted mb-4">请根据孩子在过去6个月内的表现，选择最符合的选项。</p>
                </div>
            `;

            categoryQuestions.forEach(question => {
                const questionId = question.id;
                const selectedValue = answers[questionId] || '';

                html += `
                    <div class="card mb-3">
                        <div class="card-body">
                            <h5 class="card-title">${question.question_text}</h5>
                            <div class="mt-3">
                                <div class="form-text mb-2">${question.score_description}</div>
                                <div class="btn-group w-100" role="group">
                                    <input type="radio" class="btn-check" name="question_${questionId}" id="q${questionId}_0" value="0" ${selectedValue === '0' ? 'checked' : ''}>
                                    <label class="btn btn-outline-primary" for="q${questionId}_0">0</label>

                                    <input type="radio" class="btn-check" name="question_${questionId}" id="q${questionId}_1" value="1" ${selectedValue === '1' ? 'checked' : ''}>
                                    <label class="btn btn-outline-primary" for="q${questionId}_1">1</label>

                                    <input type="radio" class="btn-check" name="question_${questionId}" id="q${questionId}_2" value="2" ${selectedValue === '2' ? 'checked' : ''}>
                                    <label class="btn btn-outline-primary" for="q${questionId}_2">2</label>

                                    <input type="radio" class="btn-check" name="question_${questionId}" id="q${questionId}_3" value="3" ${selectedValue === '3' ? 'checked' : ''}>
                                    <label class="btn btn-outline-primary" for="q${questionId}_3">3</label>

                                    <input type="radio" class="btn-check" name="question_${questionId}" id="q${questionId}_4" value="4" ${selectedValue === '4' ? 'checked' : ''}>
                                    <label class="btn btn-outline-primary" for="q${questionId}_4">4</label>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
            });

            questionsContainer.innerHTML = html;

            // 更新按钮状态
            prevCategoryBtn.style.display = categoryId > 1 ? 'block' : 'none';

            if (categoryId < categories.length) {
                nextCategoryBtn.style.display = 'block';
                submitAssessmentBtn.style.display = 'none';
                nextCategoryBtn.textContent = '下一类';
            } else {
                nextCategoryBtn.style.display = 'none';
                submitAssessmentBtn.style.display = 'block';
            }

            // 添加问题选项的事件监听
            categoryQuestions.forEach(question => {
                const questionId = question.id;
                const options = document.querySelectorAll(`input[name="question_${questionId}"]`);

                options.forEach(option => {
                    option.addEventListener('change', function() {
                        answers[questionId] = this.value;
                    });
                });
            });
        }

        // 上一类按钮点击事件
        prevCategoryBtn.addEventListener('click', function() {
            if (currentCategory > 1) {
                showCategory(currentCategory - 1);
            }
        });

        // 下一类按钮点击事件
        nextCategoryBtn.addEventListener('click', function() {
            // 检查当前类别的问题是否都已回答
            const categoryQuestions = questions[currentCategory] || [];
            let unansweredQuestions = [];

            categoryQuestions.forEach(question => {
                if (!answers[question.id]) {
                    unansweredQuestions.push(question.id);
                }
            });

            if (unansweredQuestions.length > 0) {
                // 高亮显示未回答的问题
                unansweredQuestions.forEach(questionId => {
                    const questionCard = document.querySelector(`#question_${questionId}`);
                    if (questionCard) {
                        questionCard.classList.add('border-danger');
                        // 3秒后移除高亮
                        setTimeout(() => {
                            questionCard.classList.remove('border-danger');
                        }, 3000);
                    }
                });
                showWarning('请回答所有问题后再继续');
                return;
            }

            if (currentCategory < categories.length) {
                showCategory(currentCategory + 1);
            }
        });

        // 提交评估按钮点击事件
        submitAssessmentBtn.addEventListener('click', async function() {
            // 检查是否所有问题都已回答
            let unansweredQuestions = [];

            for (const categoryId in questions) {
                questions[categoryId].forEach(question => {
                    if (!answers[question.id]) {
                        unansweredQuestions.push(question.id);
                    }
                });
            }

            if (unansweredQuestions.length > 0) {
                // 切换到包含第一个未回答问题的类别
                const firstUnansweredId = unansweredQuestions[0];
                let targetCategory = 1;

                // 查找包含未回答问题的类别
                for (const categoryId in questions) {
                    if (questions[categoryId].some(q => q.id === firstUnansweredId)) {
                        targetCategory = parseInt(categoryId);
                        break;
                    }
                }

                showCategory(targetCategory);

                // 高亮显示未回答的问题
                unansweredQuestions.forEach(questionId => {
                    const questionCard = document.querySelector(`#question_${questionId}`);
                    if (questionCard) {
                        questionCard.classList.add('border-danger');
                        // 3秒后移除高亮
                        setTimeout(() => {
                            questionCard.classList.remove('border-danger');
                        }, 3000);
                    }
                });

                showWarning(`还有 ${unansweredQuestions.length} 个问题未回答，请完成所有问题后再提交`);
                return;
            }

            await submitAssessment();
        });

        // 提交评估函数
        async function submitAssessment() {
            try {
                // 提交评估
                const response = await fetch('/apps/scales/abc-scale/submit', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        childName: childInfo.childName,
                        childAge: childInfo.childAge,
                        childGender: childInfo.childGender,
                        answers: answers
                    })
                });

                const data = await response.json();

                if (data.success) {
                    // 关闭评估模态框
                    assessmentModal.hide();

                    // 更新结果模态框内容
                    document.querySelector('#resultScore span').textContent = data.totalScore;
                    document.querySelector('#resultLevel span').textContent = data.resultLevel;
                    document.getElementById('resultDescription').textContent = data.resultDescription;

                    // 设置结果图标和颜色
                    const resultIcon = document.getElementById('resultIcon');
                    if (data.resultLevel === '正常') {
                        resultIcon.innerHTML = '<i class="fas fa-check-circle text-success fa-4x"></i>';
                    } else if (data.resultLevel === '轻度') {
                        resultIcon.innerHTML = '<i class="fas fa-exclamation-circle text-warning fa-4x"></i>';
                    } else if (data.resultLevel === '中度') {
                        resultIcon.innerHTML = '<i class="fas fa-exclamation-triangle text-orange fa-4x"></i>';
                    } else {
                        resultIcon.innerHTML = '<i class="fas fa-times-circle text-danger fa-4x"></i>';
                    }

                    // 设置查看详细结果按钮链接
                    document.getElementById('viewResultBtn').href = `/apps/scales/abc-scale/result/${data.assessmentId}`;

                    // 显示结果模态框
                    resultModal.show();

                    // 重置表单
                    childInfoForm.reset();
                    answers = {};
                } else {
                    alert('提交评估失败: ' + data.message);
                }
            } catch (error) {
                console.error('提交评估错误:', error);
                alert('提交评估失败，请稍后重试');
            }
        }
    });
</script>

</body>
</html> 
